package org.brisling.medical.queryService;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.util.DateUtil;
import org.brisling.common.util.WhereUtil;
import org.brisling.medical.domain.MedicalPathwayPatientConclusion;
import org.brisling.sysman.queryService.QueryDictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
@RequestMapping("/medicalPathwayPatientConclusion/query")
public class QueryMedicalPathwayPatientConclusion extends AbstractBaseQueryService<MedicalPathwayPatientConclusion>{

	final private int tableString = 0;
	final private int tableDouble = 1;
	final private int tableInt = 2;
	
	
	
	public QueryMedicalPathwayPatientConclusion(){
		this.moduleName = ConstSysParam.MODULE_PATHWAY_PATIENT_CONCLUSION;
		this.subSystem = ConstSysParam.SUBSYSTEM_MEDICAL;
		this.tableName = this.moduleName;
		this.clazz = MedicalPathwayPatientConclusion.class;
		typeMap = this.getTypeMap(clazz);
	
	}
//	@Autowired
//	public MedicalPathwayPatientConclusionService medicalPathwayPatientConclusionSer;
	
	@Autowired
	public QueryDictionaryService qryDictionaryService;
	
	@PersistenceContext(unitName=ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;		
	}
	
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return getBizMainPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return getBizEditPage();
	}
	
	@RequestMapping("/getListDomain.action")
	public ListDomain<MedicalPathwayPatientConclusion> getListDomain(@RequestBody(required=false) String body){		
		Map<String,Object> map = this.getBodyParam(body);
		
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Map<String,String> paramMap = (Map<String, String>) map.get(ConstSysParam.CONDITION_MAP_KEY);
		
		String dataType = "1";
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){
			if(isManageJob(userid)){
				String deptids = this.getJobDeptidAndAccountDeptids(userid);
				paramMap.put("dept_code_in", deptids);
				dataType = "2";
			}else{
				
				paramMap.put("doct_code", userid);
				dataType = "3";
			}
			//查找科室数据		
		}

		if(!dataType.equals("1")){
			paramMap.put("data_type", dataType);
		}
		
		
		map.put(ConstSysParam.CONDITION_MAP_KEY, paramMap);
		
		//查询表
		return super.getListDomainByConditionAndOrder(null, map, typeMap, orderMap, true);
		
	}
	
	/**
	 * 获取部门统计指标
	 * @param body
	 * @return
	 */
	@RequestMapping("/getDeptListDomain.action")
	public ListDomain<MedicalPathwayPatientConclusion> getDeptListDomain(@RequestBody(required=false) String body){	
		
		
		Map<String,Object> map = this.getBodyParam(body);
		
		String userid = shiroSecurityService.getCurrentUserIdentify();
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){
			if(isManageJob(userid)){
				addJobDeptConditionToMap(userid,map,"dept_code");
			}else{
				addUsridConditionToMap(userid,map,"doct_code");
			}
			//查找科室数据		
		}
		
		Map<String,String> paramMap = (Map<String, String>) map.get(ConstSysParam.CONDITION_MAP_KEY);
		if(!paramMap.containsKey("data_type"))
			paramMap.put("data_type", "1");
		
		if(!paramMap.containsKey("patient_type"))
			paramMap.put("patient_type", "1");
		
		map.put(ConstSysParam.CONDITION_MAP_KEY, paramMap);		
		
		//查询表
		return super.getListDomainByConditionAndOrder(null, map, typeMap, orderMap, true);
		
	}
	
	@RequestMapping("/getAllListDomain.action")
	public ListDomain<MedicalPathwayPatientConclusion> getAllListDomain(@RequestBody(required=false) String body){		
		
		Map<String,Object> map = this.getBodyParam(body);
		
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Map<String,String> paramMap = (Map<String, String>) map.get(ConstSysParam.CONDITION_MAP_KEY);
		
		String dataType = "1";
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){
			if(isManageJob(userid)){
				String deptids = this.getJobDeptidAndAccountDeptids(userid);
				paramMap.put("dept_code_in", deptids);
				dataType = "2";
			}else{
				
				paramMap.put("doct_code", userid);
				dataType = "3";
			}
			//查找科室数据		
		}else{
			paramMap.put("dept_code_in", "-1");
			dataType = "1";
		}		
		paramMap.put("data_type", dataType);
		
		map.put(ConstSysParam.CONDITION_MAP_KEY, paramMap);
		
		//查询表
		return super.getListDomainByConditionAndOrder(null, map, typeMap, orderMap, true);
		
	}
	
	@RequestMapping("/getList.action")
	public List<MedicalPathwayPatientConclusion> getList(@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="rows",required=false) Integer rows,
			@RequestParam(value="deptid",required=false) Integer deptid,
			@RequestParam(value="sort",required=false) String sort){		
		
		StringBuilder sb = new StringBuilder();
		String sql = "";
		if(deptid!=null){
			String whereCorse=String.format(sb.append("\"deptid\" = %1$d").toString(),deptid);
			sql = String.format(this.TW_SQL, this.tableName,whereCorse);
		}else{
			sql = String.format(this.T_SQL, this.tableName);
		}
		
		return super.getPagedList(page,rows,sql);
	}
	
	public List<MedicalPathwayPatientConclusion> getListAll(Map<String, String> map){	
		
		String sql = "";
		String whereCorse = null;					
			
		whereCorse = WhereUtil.getConditionWhereCorse(map,typeMap);
		System.out.println("whereCorse: " +whereCorse);		
		
		if(whereCorse!=null){			
			sql = String.format(this.TW_SQL, this.tableName,whereCorse);
			return super.getAllList(sql);
		}
		return new ArrayList<MedicalPathwayPatientConclusion>();		
		
	}
	/**
	 * 根据指标id查找指标信息
	 * @param id	指标id
	 * @return 指标信息记录 
	 */
	@RequestMapping("/getOne.action")
	public MedicalPathwayPatientConclusion getOne(@RequestParam(value="id",required=false) Long id){
		return super.getOne(id);
	}
	
	/**
	 * 根据指标唯一编码查找指标信息
	 * @param identify	指标唯一编码
	 * @return 指标信息记录
	 */
	@RequestMapping("/getOneByIdentify.action")
	public MedicalPathwayPatientConclusion getOneByIdentify(@RequestParam(value="identify",required=false) String identify){	
		return super.getOneByIdentify(identify);
	}	
	
	
	@RequestMapping("/getListByField.action")
	public List<MedicalPathwayPatientConclusion> getListByField(@RequestParam(value="field",required=false) String field,@RequestParam(value="fieldVal",required=false) String fieldVal){	
		return super.getListByIdentify(field,fieldVal);
	}


	@Autowired
	private ShiroSecurityService shiroSecurityService;
	
	@RequestMapping("/popPage.action")
	public ModelAndView getPopPage(){
		String userid = shiroSecurityService.getCurrentUserIdentify();
		String _page = "popMain";
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_all")){
			if(!isManageJob(userid)){				
				_page="popDetail";
			}					
		}
		return new ModelAndView("/medical/medical_pathway_patient/"+_page);
	}
	
	public List<MedicalPathwayPatientConclusion> autoMonitor(Integer year,Integer month){
		String[] yestodayMonth = null;
		if(year ==null || month ==null)
			yestodayMonth = DateUtil.getYestodayMonthDay();
		else{
			yestodayMonth = DateUtil.getMonthDay(year, month);
		}
		
		List<MedicalPathwayPatientConclusion> inlists = countMedicalPathwayPatientConclusion(yestodayMonth[2],yestodayMonth[0],yestodayMonth[1]);
		
		//查询已有数据
		List<MedicalPathwayPatientConclusion> oldLists = this.getList(yestodayMonth[2]);
		LinkedHashMap<String,MedicalPathwayPatientConclusion> lmap = new LinkedHashMap<String,MedicalPathwayPatientConclusion>();
		
		//将已有值存入临时map
		if(oldLists!=null && oldLists.size()>0){
			
			for(int i=0;i<oldLists.size();i++){
				MedicalPathwayPatientConclusion b = oldLists.get(i);
				String _key = null;
				if(b.getDoct_code()==null ){
					_key = b.getDept_code()+"-"+b.getPatient_type();
				}else{
					_key = b.getDept_code() +"-" + b.getDoct_code()+"-"+b.getPatient_type();
				}
				lmap.put(_key, b);
			}
		}
		
		
		if(inlists!=null){
			if(lmap!=null && lmap.size()>0){
				for(int i=0;i<inlists.size();i++){
					MedicalPathwayPatientConclusion b = inlists.get(i);
					String _key = null;
					if(b.getDoct_code()==null ){
						_key = b.getDept_code()+"-"+b.getPatient_type();
					}else{
						_key = b.getDept_code() +"-" + b.getDoct_code()+"-"+b.getPatient_type();
					}
					if(lmap.containsKey(_key)){
						inlists.get(i).setId(lmap.get(_key).getId());
					}
				}
			}
			return inlists;
//			medicalPathwayPatientConclusionSer.saveList(inlists);	
			
		}	
		return null;
	}

	private List<MedicalPathwayPatientConclusion> getList(String string) {
		// TODO Auto-generated method stub
		String sql = String.format("select * from %1$s where monitor_year_month='%2$s'",this.tableName,string); 
		//查询表
		return super.getAllList(sql);
		//return null;
	}

	private List<MedicalPathwayPatientConclusion> countMedicalPathwayPatientConclusion(String year_month, String startDate,
			String endDate) {
		// TODO Auto-generated method stub
		String[] sqlids = {"medical_pathway_all","medical_pathway_dept","medical_pathway_doct"};
		//统计全院数据-住院
		String[] standerSql = {
				"SELECT '1' data_type, '2' patient_type, count (mpp.paient_id) variationAmount,count (mpp.paient_id) accessAmount, SUM (case when mpp.VARIATION = 1 then 0 else 1 end) completeAmount, SUM(mpp.hospitalization_day) hospitalizationTotalDay, SUM( CASE WHEN mpp.hospitalized30 = '1' THEN 1 ELSE 0 END) backToHospitalizationAmount, SUM( CASE WHEN mpp.unplanned_surgery = '1' THEN 1 ELSE 0 END) againSurgeryAmount, SUM( CASE WHEN mpp.complication = '1' THEN 1 ELSE 0 END) complicationAmount, SUM( CASE WHEN mpp.turbiCure = '1' THEN 1 ELSE 0 END) cureAmount, '-1' dept_code FROM ( (SELECT * FROM medical_pathway_patient mmpp WHERE mmpp.createtime >= to_date('%1$s 00:00:00', 'yyyy-mm-dd hh24:Mi:ss') AND mmpp.createtime   <= to_date('%2$s 23:59:59', 'yyyy-mm-dd hh24:Mi:ss') ) mpp LEFT JOIN v_medical_inpatient mp ON to_char(mpp.paient_id) = mp.zyhm) LEFT JOIN v_sysman_user su ON su.doct_code = mp.doct_code group by '1', '2', '-1'",
				"SELECT '2' data_type, '2' patient_type, count (mpp.paient_id) variationAmount,count(mpp.paient_id) accessAmount, SUM (case when mpp.VARIATION = 1 then 0 else 1 end) completeAmount, SUM(mpp.hospitalization_day) hospitalizationTotalDay, SUM( CASE WHEN mpp.hospitalized30 = '1' THEN 1 ELSE 0 END) backToHospitalizationAmount, SUM( CASE WHEN mpp.unplanned_surgery = '1' THEN 1 ELSE 0 END) againSurgeryAmount, SUM( CASE WHEN mpp.complication = '1' THEN 1 ELSE 0 END) complicationAmount, SUM( CASE WHEN mpp.turbiCure = '1' THEN 1 ELSE 0 END) cureAmount, su.deptid dept_code, su.deptname dept_name FROM ( (SELECT * FROM medical_pathway_patient mmpp WHERE mmpp.createtime >= to_date('%1$s 00:00:00', 'yyyy-mm-dd hh24:Mi:ss') AND mmpp.createtime   <= to_date('%2$s 23:59:59', 'yyyy-mm-dd hh24:Mi:ss') ) mpp LEFT JOIN v_medical_inpatient mp ON to_char(mpp.paient_id) = mp.zyhm) LEFT JOIN v_sysman_user su ON su.doct_code = mp.doct_code GROUP BY '2', su.deptid, su.deptname",
				//"SELECT '3' data_type, '2' patient_type, count (mpp.paient_id) variationAmount,count(mpp.paient_id) accessAmount, SUM (case when mpp.VARIATION = 1 then 0 else 1 end) completeAmount, SUM(mpp.hospitalization_day) hospitalizationTotalDay, SUM( CASE WHEN mpp.hospitalized30 = '1' THEN 1 ELSE 0 END) backToHospitalizationAmount, SUM( CASE WHEN mpp.unplanned_surgery = '1' THEN 1 ELSE 0 END) againSurgeryAmount, SUM( CASE WHEN mpp.complication = '1' THEN 1 ELSE 0 END) complicationAmount, SUM( CASE WHEN mpp.turbiCure = '1' THEN 1 ELSE 0 END) cureAmount, su.name doct_name, su.doct_code doct_code, su.deptid dept_code, su.deptname dept_name, mpp.disease_id, mpp.disease_name FROM ( (SELECT * FROM medical_pathway_patient mmpp WHERE mmpp.createtime >= to_date('%1$s 00:00:00', 'yyyy-mm-dd hh24:Mi:ss') AND mmpp.createtime   <= to_date('%2$s 23:59:59', 'yyyy-mm-dd hh24:Mi:ss') ) mpp LEFT JOIN medical_inpatient mp ON to_char(mpp.paient_id) = mp.zyhm) LEFT JOIN v_sysman_user su ON su.doct_code = mp.doct_code GROUP BY su.name, '3', '2', su.doct_code, su.deptid, su.deptname, mpp.disease_id, mpp.disease_name",
				"SELECT '3' data_type, '2' patient_type, count (mpp.paient_id) variationAmount,count(mpp.paient_id) accessAmount, SUM (case when mpp.VARIATION = 1 then 0 else 1 end) completeAmount, SUM(mpp.hospitalization_day) hospitalizationTotalDay, SUM( CASE WHEN mpp.hospitalized30 = '1' THEN 1 ELSE 0 END) backToHospitalizationAmount, SUM( CASE WHEN mpp.unplanned_surgery = '1' THEN 1 ELSE 0 END) againSurgeryAmount, SUM( CASE WHEN mpp.complication = '1' THEN 1 ELSE 0 END) complicationAmount, SUM( CASE WHEN mpp.turbiCure = '1' THEN 1 ELSE 0 END) cureAmount, su.name doct_name, su.doct_code doct_code, su.deptid dept_code, su.deptname dept_name FROM ( (SELECT * FROM medical_pathway_patient mmpp WHERE mmpp.createtime >= to_date('%1$s 00:00:00', 'yyyy-mm-dd hh24:Mi:ss') AND mmpp.createtime   <= to_date('%2$s 23:59:59', 'yyyy-mm-dd hh24:Mi:ss') ) mpp LEFT JOIN v_medical_inpatient mp ON to_char(mpp.paient_id) = mp.zyhm) LEFT JOIN v_sysman_user su ON su.doct_code = mp.doct_code GROUP BY su.name, '3', '2', su.doct_code, su.deptid, su.deptname"
		};
		List<String> sqls = new ArrayList<String>();
		for(int i = 0;i<sqlids.length;i++){
			String sql = qryDictionaryService.getSqlByBizcode(sqlids[i]);
			if(sql == null){
				sql = standerSql[i];
			}
			sql = sql.format(sql, startDate, endDate);
			System.out.println(sql);
			if(sql!=null){
				sqls.add(sql);
			}
		}
		//所有数据
		List<MedicalPathwayPatientConclusion> lists = super.monitorCountBase(year_month,startDate,endDate,sqls);		
		
		Long amountNum = 0L;
		for(int i = 0; i < lists.size(); i++){
			MedicalPathwayPatientConclusion tempList = lists.get(i);
			amountNum = tempList.getVariationAmount();
			tempList.setAccessPer((double)tempList.getAccessAmount() / (double)amountNum);
//			tempList.setAccessPer(1.0);
			tempList.setCompletePer((double)tempList.getCompleteAmount() / (double)amountNum);
			tempList.setAgainSurgeryPer((double)tempList.getAgainSurgeryAmount() / (double)amountNum);
			tempList.setBackToHospitalizationPer((double)tempList.getBackToHospitalizationAmount() / (double)amountNum);
			tempList.setCurePer((double)tempList.getCureAmount() / (double)amountNum);
			tempList.setVariationPer(tempList.getAccessPer() - tempList.getCompletePer());
//			tempList.setP
			tempList.setMonitor_year_month(DateUtil.getYestodayMonthDay()[2]);
		}
		return lists;
	}
}
